import { awaitWrap, decompress } from '@src/assets/js/tool'
import { Dialog, Skeleton, Toast } from 'antd-mobile'
import { useEffect, useMemo } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import style from './index.module.less'
import { loginRequest } from './ajax'
import { logout, setToken, setUserInfo } from '@src/redux/reducers/basic'
import { useAppDispatch } from '@src/redux/hook'
import { root } from '@src/assets/js/config'

async function loginHandle (str, h, dispatch) {
  Toast.show({
    content: '登录中',
    icon: 'loading',
    duration: 0
  })
  const [e, d] = await awaitWrap(loginRequest(str))
  if (e === null && d !== null) {
    Toast.clear()
    afterLogin(h, d, dispatch)
  } else {
    Toast.clear()
    h.push(`${root}/gate/home`)
  }
}

function afterLogin (h, data, dispatch) {
  if (data.userInfo.is_auth !== 1) {
    h.push(`${root}/gate/verification`)
  } else {
    h.replace(`${root}/gate/home`)
  }
  const u = data.userInfo
  if (typeof u.mobile === 'string' && u.mobile.length > 0) {
    u.mobile = decompress(u.mobile)
  }
  Dialog.show({
    content: <span style={{ color: 'red' }}>此系统为非涉密系统，严禁上传涉密信息。</span>,
    actions: [{ key: '0', text: '确定' }],
    closeOnAction: true
  })
  dispatch(setToken(data.token))
  dispatch(setUserInfo(u))
}

function Main () {
  const l = useLocation()
  const h = useHistory()
  const dispatch = useAppDispatch()
  const str = useMemo(() => {
    if (l.search.indexOf('?encodeStr=') === 0) {
      return l.search.replace('?encodeStr=', '')
    }
    return ''
  }, [l])
  useEffect(() => {
    dispatch(logout())
  }, [dispatch])
  useEffect(() => {
    if (str) {
      loginHandle(str, h, dispatch)
    }
  }, [str, h, dispatch])
  return (
    <div className={style.container}>
      <Skeleton.Title animated />
      <Skeleton.Paragraph lineCount={5} animated />
    </div>
  )
}

export default Main
